package cn.gailvlun.gll.presentation.apartment.vm

import android.arch.lifecycle.ViewModel
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.net.Member
import cn.gailvlun.gll.net.apartment.room.Room
import cn.gailvlun.gll.net.base.Profile
import io.realm.Realm
import io.realm.RealmObject


class ApartmentDetailViewModel: ViewModel {

    private var realm: Realm?

    constructor() : super() {
        realm = Realm.getInstance(ChatDB2.getConfiguration())

    }

    fun getChatUser(userId: Int): Profile? {
        return realm!!.where(Profile::class.java).equalTo("id", userId).findFirst()
    }

    fun saveRoom(room: Room) {
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(room)
        }
    }

    fun saveMember(member: Member) {
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(member)
        }
    }

    fun saveProfile(profile: Profile) {
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(profile)
        }
    }

    fun save(obj: RealmObject) {
        realm!!.executeTransaction { realm->
            realm.insertOrUpdate(obj)
        }
    }

    override fun onCleared() {
        realm?.close()
        realm = null

        super.onCleared()
    }
}